//
//  ViewController.m
//  myBleMulti
//
//  Created by yorkfeng on 16/11/14.
//  Copyright © 2016年 yorkfeng. All rights reserved.
//

#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>

#define UUIDSendDataService  @"0xFFE5"
#define UUIDSendDataCharateristic @"0xFFE9"
#define UUIDReadDataService  @"0xFFE0"
#define UUIDReadDataCharateristic @"0xFFE4"

#define UUIDInfoService  @"0xFF90"
#define UUIDDeviceNameCharateristic @"0xFF91"

@interface ViewController () <CBCentralManagerDelegate> {
    //系统蓝牙设备管理对象，可以把他理解为主设备，通过他，可以去扫描和链接外设
    CBCentralManager *manager;
    //发现设备数组
    NSMutableArray *discoverPeripherals;
    CBPeripheral *aPeripheralLeft, *aPeripheralRight;
    NSMutableArray *aRSSI;
    
//    CBService *SendDataService;
    CBCharacteristic *SendDataCharateristicLeft, *SendDataCharateristicRight;
    CBCharacteristic *ReadDataCharateristicLeft, *ReadDataCharateristicRight;
    CBCharacteristic *DeviceNameCharateristicLeft, *DeviceNameCharateristicRight;
    
    __weak IBOutlet UITableView *tabLeft;
    __weak IBOutlet UITableView *tabRight;
    
    __weak IBOutlet UILabel *labLeft;
    __weak IBOutlet UILabel *labRight;
    
    __weak IBOutlet UITextView *tvLeft;
    __weak IBOutlet UITextView *tvRight;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [tabLeft setDelegate:(id)self];
    [tabRight setDelegate:(id)self];
    [tabLeft setDataSource:(id)self];
    [tabRight setDataSource:(id)self];
    
    //初始化并设置委托和线程队列，最好一个线程的参数可以为nil，默认会就main线程
    manager = [[CBCentralManager alloc]initWithDelegate:self queue:dispatch_get_main_queue()];
    
    //持有发现的设备
    discoverPeripherals = [[NSMutableArray alloc]init];
    
    aRSSI = [[NSMutableArray alloc]init];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [manager stopScan];
    });
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark ble
-(void)centralManagerDidUpdateState:(CBCentralManager *)central {
    
    switch (central.state) {
        case CBCentralManagerStateUnknown:
            NSLog(@">>>CBCentralManagerStateUnknown");
            break;
        case CBCentralManagerStateResetting:
            NSLog(@">>>CBCentralManagerStateResetting");
            break;
        case CBCentralManagerStateUnsupported:
            NSLog(@">>>CBCentralManagerStateUnsupported");
            break;
        case CBCentralManagerStateUnauthorized:
            NSLog(@">>>CBCentralManagerStateUnauthorized");
            break;
        case CBCentralManagerStatePoweredOff:
            NSLog(@">>>CBCentralManagerStatePoweredOff");
            break;
        case CBCentralManagerStatePoweredOn:
            NSLog(@">>>CBCentralManagerStatePoweredOn");
            //开始扫描周围的外设
            /*
             第一个参数nil就是扫描周围所有的外设，扫描到外设后会进入
             - (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI;
             */
            [central scanForPeripheralsWithServices:nil options:nil];
            break;
        default:
            break;
    }
    
}

//扫描到设备会进入方法
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI{
    
    NSLog(@"扫描到设备:%@",peripheral.name);
    /*
     一个主设备最多能连7个外设，每个外设最多只能给一个主设备连接,连接成功，失败，断开会进入各自的委托
     - (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral;//连接外设成功的委托
     - (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//外设连接失败的委托
     - (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;//断开外设的委托
     */
    for (CBPeripheral *item in discoverPeripherals)    //防止添加同一个外设
        if ([peripheral.identifier.UUIDString isEqualToString:item.identifier.UUIDString])
            return;
    [discoverPeripherals addObject:peripheral];
    [aRSSI addObject:RSSI];
    [tabRight reloadData];
    [tabLeft reloadData];
    NSLog(@"add success");
    
}

//连接到Peripherals-失败
-(void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@">>>连接到名称为（%@）的设备-失败,原因:%@",[peripheral name],[error localizedDescription]);
}

//Peripherals断开连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@">>>外设连接断开连接 %@: %@\n", [peripheral name], [error localizedDescription]);
    
    if ([peripheral isEqual:aPeripheralLeft]) {
        [labLeft setText:@"断开连接"];
    }
    if ([peripheral isEqual:aPeripheralRight]) {
        [labRight setText:@"断开连接"];
    }
    
}
//连接到Peripherals-成功
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    NSLog(@">>>连接到名称为（%@）的设备-成功",peripheral.name);
 
    //设置的peripheral委托CBPeripheralDelegate
    //@interface ViewController : UIViewController<CBCentralManagerDelegate,CBPeripheralDelegate>
    [peripheral setDelegate:(id)self];
    //扫描外设Services，成功后会进入方法：-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error{
    [peripheral discoverServices:nil];
    
    if ([peripheral isEqual:aPeripheralLeft]) {
        [labLeft setText:[NSString stringWithFormat:@"%@", peripheral.name]];
    }
    if ([peripheral isEqual:aPeripheralRight]) {
        [labRight setText:[NSString stringWithFormat:@"%@", peripheral.name]];
    }
}

//扫描到Services
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    //      NSLog(@">>>扫描到服务：%@",peripheral.services);
    if (error) {
        NSLog(@">>>Discovered services for %@ with error: %@", peripheral.name, [error localizedDescription]);
        return;
    }
    
    for (CBService *service in peripheral.services) {
        NSLog(@"%@",service.UUID);
        //扫描每个service的Characteristics，扫描到后会进入方法： -(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
        [peripheral discoverCharacteristics:nil forService:service];
    }
    
}

//扫描到Characteristics
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error{
    if (error) {
        NSLog(@"error Discovered characteristics for %@ with error: %@", service.UUID, [error localizedDescription]);
        return;
    }
    
    if ([[service UUID] isEqual:[CBUUID UUIDWithString:UUIDSendDataService]] || [[service UUID] isEqual:[CBUUID UUIDWithString:UUIDReadDataService]] || [[service UUID] isEqual:[CBUUID UUIDWithString:UUIDInfoService]]) {
    
        for (CBCharacteristic *characteristic in [service characteristics]) {
            //                NSLog(@"发现特值UUID: %@\n", [characteristic UUID]);
            if ([[characteristic UUID] isEqual:[CBUUID UUIDWithString:UUIDSendDataCharateristic]]) {
                if ([peripheral isEqual:aPeripheralLeft]) {
                    SendDataCharateristicLeft = characteristic;
                }
                if ([peripheral isEqual:aPeripheralRight]) {
                    SendDataCharateristicRight = characteristic;
                }
                
                NSLog(@"发现特征值SendDataCharateristic");
                // 等到写通道初始化完成才发信号
//                if (self.delegate) {
//                    // 判断是否实现了该方法
//                    if([(id)self.delegate respondsToSelector:@selector(didConnect)]){
//                        [self.delegate didConnect];
//                    }
//                }
            }
            else if ([[characteristic UUID] isEqual:[CBUUID UUIDWithString:UUIDReadDataCharateristic]])
            {
                // FFF2 IO设置
                if ([peripheral isEqual:aPeripheralLeft]) {
                    ReadDataCharateristicLeft = characteristic;
                }
                if ([peripheral isEqual:aPeripheralRight]) {
                    ReadDataCharateristicRight = characteristic;
                }
                
                NSLog(@"发现特征值ReadDataCharateristic");
                // 监听读通道
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                
            }
            else if ([[characteristic UUID] isEqual:[CBUUID UUIDWithString:UUIDDeviceNameCharateristic]])
            {
                // 蓝牙设备名
                if ([peripheral isEqual:aPeripheralLeft]) {
                    DeviceNameCharateristicLeft = characteristic;
                }
                if ([peripheral isEqual:aPeripheralRight]) {
                    DeviceNameCharateristicRight = characteristic;
                }
                NSLog(@"发现特征值DeviceNameCharateristic");
                // 监听设备名称通道
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            }
        }
    }
    
}

//获取的charateristic的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    //打印出characteristic的UUID和值
    //!注意，value的类型是NSData，具体开发时，会根据外设协议制定的方式去解析数据
    NSLog(@"didUpdateValueForCharacteristic uuid:%@  value:%@",characteristic.UUID,characteristic.value);
    
    if ([peripheral isEqual:aPeripheralLeft]) {
        [tvLeft setText:[NSString stringWithFormat:@"%@\n%@", tvLeft.text, characteristic.value]];
    }
    if ([peripheral isEqual:aPeripheralRight]) {
        [tvRight setText:[NSString stringWithFormat:@"%@\n%@", tvRight.text, characteristic.value]];
    }
}

//搜索到Characteristic的Descriptors
-(void)peripheral:(CBPeripheral *)peripheral didDiscoverDescriptorsForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    
    //打印出Characteristic和他的Descriptors
    NSLog(@"characteristic uuid:%@",characteristic.UUID);

    for (CBDescriptor *d in characteristic.descriptors) {
        NSLog(@"Descriptor uuid:%@",d.UUID);
    }
}

//获取到Descriptors的值
-(void)peripheral:(CBPeripheral *)peripheral didUpdateValueForDescriptor:(CBDescriptor *)descriptor error:(NSError *)error{
    //打印出DescriptorsUUID 和value
    //这个descriptor都是对于characteristic的描述，一般都是字符串，所以这里我们转换成字符串去解析
    NSLog(@"characteristic uuid:%@  value:%@",[NSString stringWithFormat:@"%@",descriptor.UUID],descriptor.value);
}

//写数据
-(void)writeCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic value:(NSData *)value {
    
    //打印出 characteristic 的权限，可以看到有很多种，这是一个NS_OPTIONS，就是可以同时用于好几个值，常见的有read，write，notify，indicate，知知道这几个基本就够用了，前连个是读写权限，后两个都是通知，两种不同的通知方式。
    /*
     typedef NS_OPTIONS(NSUInteger, CBCharacteristicProperties) {
     CBCharacteristicPropertyBroadcast												= 0x01,
     CBCharacteristicPropertyRead													= 0x02,
     CBCharacteristicPropertyWriteWithoutResponse									= 0x04,
     CBCharacteristicPropertyWrite													= 0x08,
     CBCharacteristicPropertyNotify													= 0x10,
     CBCharacteristicPropertyIndicate												= 0x20,
     CBCharacteristicPropertyAuthenticatedSignedWrites								= 0x40,
     CBCharacteristicPropertyExtendedProperties										= 0x80,
     CBCharacteristicPropertyNotifyEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)		= 0x100,
     CBCharacteristicPropertyIndicateEncryptionRequired NS_ENUM_AVAILABLE(NA, 6_0)	= 0x200
     };
     
     */
    NSLog(@"%lu", (unsigned long)characteristic.properties);
    
    
    //只有 characteristic.properties 有write的权限才可以写
    if(characteristic.properties & CBCharacteristicPropertyWrite) {
        /*
         最好一个type参数可以为CBCharacteristicWriteWithResponse或type:CBCharacteristicWriteWithResponse,区别是是否会有反馈
         */
        [peripheral writeValue:value forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
    }else {
        NSLog(@"该字段不可写！");
    }
    
    
}

//设置通知
-(void)notifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {
    //设置通知，数据通知会进入：didUpdateValueForCharacteristic方法
    [peripheral setNotifyValue:YES forCharacteristic:characteristic];
    
}

//取消通知
-(void)cancelNotifyCharacteristic:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic {
    
    [peripheral setNotifyValue:NO forCharacteristic:characteristic];
}

#pragma mark btn
- (IBAction)btnScan:(id)sender {
    [discoverPeripherals removeAllObjects];
    [tabLeft reloadData];
    [tabRight reloadData];
    [manager scanForPeripheralsWithServices:nil options:nil];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [manager stopScan];
    });
}

- (IBAction)btnSendLeft:(id)sender {
    unsigned char data[8] = {0,0,0,0,0,0,0,0};
    
    data[0] = 0xA0;
    data[1] = 0xB1;
    data[2] = 0x55;
    data[3] = 0x00;
    data[4] = 0x00;
    data[5] = 0x00;
    data[6] = 0x01;
    data[7] = 0x58;
    
    [aPeripheralLeft writeValue:[NSData dataWithBytes:data length:8] forCharacteristic:SendDataCharateristicLeft type:CBCharacteristicWriteWithResponse];
}

- (IBAction)btnSendRight:(id)sender {
    unsigned char data[8] = {0,0,0,0,0,0,0,0};
    
    data[0] = 0xA0;
    data[1] = 0xB1;
    data[2] = 0x55;
    data[3] = 0x00;
    data[4] = 0x00;
    data[5] = 0x00;
    data[6] = 0x01;
    data[7] = 0x58;
    
    [aPeripheralRight writeValue:[NSData dataWithBytes:data length:8] forCharacteristic:SendDataCharateristicRight type:CBCharacteristicWriteWithResponse];}

- (IBAction)btnClearLeft:(id)sender {
    [tvLeft setText:@""];
}

- (IBAction)btnClearRight:(id)sender {
    [tvRight setText:@""];
}

#pragma mark table
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSUInteger row = [indexPath row];
    
    CBPeripheral *peripheral = discoverPeripherals[row];
    
    if ([tableView isEqual:tabLeft]) {
        aPeripheralLeft = peripheral;
    }else {
        aPeripheralRight = peripheral;
    }
    
    [manager connectPeripheral:peripheral options:nil];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [discoverPeripherals count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView
                             dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                initWithStyle:UITableViewCellStyleSubtitle
                reuseIdentifier:CellIdentifier];
    }
    
    // Configure the cell...
    
    NSUInteger row = [indexPath row];
    CBPeripheral *item = discoverPeripherals[row];
    
    NSString *tmpString = [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@           RSSI:%@", item.name, aRSSI[row]]];
    
    cell.textLabel.text = tmpString;        //设备名,RSSI
    cell.detailTextLabel.text = item.identifier.UUIDString;     //设备uuid
    
    return cell;
}

@end
